package cz.proks.schoolpupilbook.gwt.core.handler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;

import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.CourseService;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.widget.common.CourseForm;
import cz.proks.schoolpupilbook.gwt.widget.common.CourseForm.SubmitEvent;
import cz.proks.schoolpupilbook.shared.domain.Course;

public class CourseFormHandler implements CourseForm.SubmitEvent.SubmitEventHandler{
	@Override
	public void onSubmit(SubmitEvent event) {
		CourseService courseService = ServiceFactory.getCourseService();
		Course course = createCourse(event);
		
		courseService.save(course, new ResultNotifiable<Void>() {
			
			@Override
			public void onSucces(Void object) {
				History.back();
				
			}
			
			@Override
			public void onError(Throwable t) {
				Window.alert("Failed to save course: " + t.getLocalizedMessage());
			}
		});
	}
	
	private Course createCourse(SubmitEvent event) {
		Course course = new Course();
		
		course.setId(event.getId());
		course.setCode(event.getCode());
		course.setName(event.getName());
		
		return course;
	}
}
